package com.ingenico.insider.swing;

import java.awt.event.ActionEvent;
import java.awt.geom.Rectangle2D;

import javax.swing.AbstractAction;

import com.ingenico.insider.services.impl.CanvasSupplier;

import edu.umd.cs.piccolo.PCamera;
import edu.umd.cs.piccolo.util.PAffineTransform;
import edu.umd.cs.piccolo.util.PBounds;
import edu.umd.cs.piccolo.util.PDimension;

public class ZoomFitAction extends AbstractAction {
	/**
	 * Generated Serial Version UID
	 */
	private static final long serialVersionUID = 1726347854963501527L;
	
	@Override
	public void actionPerformed(ActionEvent e) {
		final PCamera camera = CanvasSupplier.getInstance().getCanvas().getCamera(); 
		final Rectangle2D cameraLayersBound = camera.getUnionOfLayerFullBounds();

		final PBounds cameraViewBounds = camera.getViewBounds();
		final PDimension delta = cameraViewBounds.deltaRequiredToCenter(cameraLayersBound);
		final PAffineTransform newTransform = camera.getViewTransform();

		newTransform.translate(delta.width, delta.height);
		
		final double scaleX = cameraViewBounds.getWidth() / cameraLayersBound.getWidth();
		final double scaleY = cameraViewBounds.getHeight() / cameraLayersBound.getHeight();
		if (scaleX != Double.POSITIVE_INFINITY && scaleX != 0 && scaleY != Double.POSITIVE_INFINITY && scaleY != 0) {
			newTransform.scaleAboutPoint(scaleX, scaleY, cameraLayersBound.getCenterX(), cameraLayersBound.getCenterY());
		}

		camera.animateViewToTransform(newTransform, 0);
	}
}
